<template>
    <div class="scene">
        <div id="div3d"></div>
        <div class="btn-wrap">
            <div>
                地球场景:
                <button @click="changeMap(1)">切换效果1</button>
                <button @click="changeMap(2)">切换效果2</button>
            </div>
            <div>
                加载园区：
                <button @click="createCampus">加载园区</button>
                <button @click="initTwinsManager">初始化点位管理器</button>
                <button @click="destroyTwins">销毁点位</button>
                <div>
                    <button @click="loadTwins('normal')">
                        加载当前层级点位(normal)
                    </button>
                    <button @click="loadTwins('batch')">
                        加载当前层级点位(batch)
                    </button>
                    <button @click="loadTwins('splitNormal')">
                        加载当前层级点位(splitNormal)
                    </button>
                    <button @click="loadTwins('splitBatch')">
                        加载当前层级点位(splitBatch)
                    </button>
                </div>
            </div>
            <div>
                倾斜摄影:
                <button @click="loadQxsy">加载倾斜摄影</button>
                <button @click="destroyQxsy">销毁倾斜摄影</button>
            </div>
            <div>
                地球点位:
                <button @click="getTwinsData">获取地球孪生体数据</button>
                <div>
                    <button @click="loadGeoPoint">加载点</button>
                    <button @click="destroyGeoPoint">删除点</button>
                </div>
                <div>
                    <button @click="loadGeoLine">加载线</button>
                    <button @click="destroyGeoLine">删除线</button>
                </div>
                <div>
                    <button @click="loadGeoPolygon">加载面</button>
                    <button @click="destroyGeoPolygon">删除面</button>
                </div>
                <div>
                    <button @click="loadBoundary">加载围栏</button>
                    <button @click="deleteBoundary">删除围栏图层</button>
                </div>
                <div>
                    <button @click="loadRouteLine">加载RouteLine</button>
                    <button @click="deleteRouteLine">删除RouteLine图层</button>
                </div>
            </div>
        </div>
    </div>
</template>

<script lang="ts" setup>
import testMarker from '@/assets/img/testMarker.png';
import { init } from '@/utils/default';
import { sceneCode } from '@/utils';
// 初始化thingjs实例
const initScene = async () => {
    window.app = await window.TiIns.createContainer({
        container: 'div3d',
        background: '#000000',
    });

    await init(); // 初始化地球
};

// 加载地球（根据后台效果包管理上传地形）
/* async function loadMap() {
    const effectList = await window.TiIns.Core.Api.getEffectPackages();
    let useEffect = null;
    if (effectList.data?.rows.length) {
        useEffect = effectList.data?.rows.find((effect: any) => effect.kind === 1);
    }
    if (!useEffect) return;
    const mapManagerIns = window.TiIns.MapManager({
        app: window.app,
        url: `${window.TiIns.Core.httpOpt.previewEffectUrl}${useEffect.code}/${useEffect.version}/map.json`,
        resourcePrefix: `${window.TiIns.Core.httpOpt.previewEffectUrl}${useEffect.code}/${useEffect.version}`,
        xAngleLimitRange: [0, 90],
        leftInteractive: true,
        isProxima: false,
        ajaxAsync: false,
        loadDataFirst: false,
        mapLoaded: () => {
            console.log('地球加载完毕');
        },
    });
} */

// 加载地球（根据本地资源地图数据加载）
/* const loadMap = () => {
    window.mapManagerIns = window.TiIns.MapManager({
        app: window.app,
        url: '/test/testMap/map/map.json',
        resourcePrefix: '/test/testMap/map',
        loadDataFirst: true,
        mapLoaded: () => {
            console.log('加载完毕');
            // 初始化地图孪生体加载类
            window.mapTwinsManagerIns = window.TiIns.MapTwinsManager(window.mapManagerIns.map, window.TiIns.Core);
            window.map = window.mapManagerIns.map;
        },
    });
}; */

/* 加载地球 */
/* const loadMap = () => {
    window.app.create({
        type: 'Map',
        url: 'https://city.thingjs.com/ra/file/fetch/df/file/0AD4BC0DB2868ACD7CCA47F0BA0CC11B37C20DEFA71F26D79AA43D91A05F6F8A51F70274C3E492E636B1923AB5B9A2A49C4F8E802C534C620DBDFDD513D529D68D07C6C209711261/map.json',
        complete: (event: any) => {
            console.log(event);
            const terrainLayer = window.app.query('.TerrainLayer')[0];
            terrainLayer.url = ''; // 移除地形
        },
    });
}; */

// 加载园区
const createCampus = () => {
    window.campusManagerIns = window.TiIns.CampusManager({
        app: window.app, // THINGJS实例
        core: window.TiIns.Core, // 核心实例
        sceneCode,
        flyToSetting: true, // 园区，建筑，楼层默认飞到设置视角 - 默认true
        initChildScene: true, // 加载主场景时是否加载子场景 默认false
        lon: 109.19603656797783,
        lat: 34.6477393474472,
        height: -10, // 离地高度
        angle: 0,
        childSceneBeginLoad: () => {
            console.log('子场景开始加载');
        },
        childSceneLoaded: () => {
            console.log('子场景加载完毕');
        },
        sceneLoaded: () => {
            console.log('主场景加载完毕');
            // 加载效果模板
            // loadEffect()
            window.app.camera.flyTo(window.app.query('.Campus')[0]);
        },
    });
};

// 切换地球效果
const changeMap = (num: number) => {
    if (num === 1) {
        window.mapManagerIns.changeEffect({
            url: '/test/testMap/map2/map.json',
            resourcePrefix: '/test/testMap/map2',
        });
    }
    if (num === 2) {
        window.mapManagerIns.changeEffect({
            url: '/test/testMap/map/map.json',
            resourcePrefix: '/test/testMap/map',
        });
    }
};

// 加载倾斜摄影
const loadQxsy = () => {
    window.mapManagerIns.createTile3dLayer(
        {
            name: 'QXSY', // 倾斜摄影图层名称
            url: 'http://10.203.1.250:10007/tileset.json', // 倾斜摄影服务url
            offsetHeight: 500,
        },
        (object: any) => {
            console.log('倾斜摄影加载完毕');
            // 倾斜摄影定位
            setTimeout(() => {
                object.flyToLayer();
            }, 1000);
        }
    );
};
// 销毁倾斜摄影
const destroyQxsy = () => {
    window.mapManagerIns.destroyLayer('QXSY');
};
// 点数据
let pointData: any = [];
// 线数据
let lineData: any = [];
// 面数据
let polygonData: any = [];
// 获取地球点位数据
const getTwinsData = () => {
    window.mapTwinsManagerIns.getMapTwinData(
        ['DI_TU_DIAN', 'DI_TU_XIAN', 'DI_TU_MIAN'],
        (data: any) => {
            console.log('获取数据', data);
            pointData = data['DI_TU_DIAN[]'];
            lineData = data['DI_TU_XIAN[]'];
            polygonData = data['DI_TU_MIAN[]'];
        }
    );
};
// 加载GeoPoint
const loadGeoPoint = () => {
    if (pointData.length === 0) return;
    pointData.forEach((point: any) => {
        // 创建点位
        window.mapTwinsManagerIns.createGeoPoint({
            id: point.uuid,
            name: '点',
            layerName: '地图点',
            coordinates: JSON.parse(point.gcj02_position),
            userData: point,
            offsetHeight: 100,
            renderer: {
                // 参考GeoPointRenderer
                type: 'model',
                url: '/test/testModel/dianwei',
                // type: 'image',
                // url: testMarker,
                size: 100,
                // alwaysOnTop: true,
                playAnimation: true,
                animationName: '_defaultAnim_',
                animationLoopType: window.THING.LoopType.Repeat,
            },
            customMarker: {
                el: createEl(),
                // url: testMarker,
                // keepSize: false,
                size: 100,
                // localPosition: [0, 10, 0],
                // pivot: [1, 1],
                // alwaysOnTop: false
            },
            modelCb: (obj: any) => {
                console.log('单个模型创建完成', obj);
                obj.children[0].style.color = '#0ce2df';
            },
            markerCb: (obj: any) => {
                console.log('单个marker创建完成', obj);
                // 添加点击事件等
                obj.on('singleclick', (e: any) => {
                    console.log('点击', e);
                });
            },
        });
    });
};
// 删除GeoPoint
const destroyGeoPoint = () => {
    const pointLayer = window.app.query('地图点')[0];
    if (pointLayer) {
        pointLayer.destroy();
    }
};
// 创建地图线
const loadGeoLine = () => {
    lineData.forEach((line: any) => {
        window.mapTwinsManagerIns.createGeoLine({
            id: line.uuid,
            name: '线',
            layerName: '地图线',
            coordinates: JSON.parse(line.gcj02_position),
            userData: line,
            offsetHeight: 100,
            renderer: {
                // 参考GeoLineRenderer
                type: 'image',
                lineType: 'Pipe',
                imageUrl: '/test/testImg/routeLine.png',
                width: 10,
                textureWrap: 10,
            },
            customMarker: {
                // el: createEl(),
                url: testMarker,
                // keepSize: false,
                size: 100,
                // localPosition: [0, 10, 0],
                // pivot: [1, 1],
                // alwaysOnTop: false
            },
            modelCb: (obj: any) => {
                console.log('单个线创建', obj);
            },
            markerCb: (obj: any) => {
                console.log('单个marker创建', obj);
                // 添加点击事件等
            },
        });
    });
};
// 删除地图线
const destroyGeoLine = () => {
    const layer = window.app.query('地图线')[0];
    if (layer) {
        layer.destroy();
    }
};
// 创建地图面
const loadGeoPolygon = () => {
    if (polygonData.length === 0) return;
    polygonData.forEach((polygon: any) => {
        // 创建点位
        window.mapTwinsManagerIns.createGeoPolygon({
            id: polygon.uuid,
            name: '面',
            layerName: '地图面',
            coordinates: JSON.parse(polygon.gcj02_position),
            userData: polygon,
            offsetHeight: 10,
            renderer: {
                // 参考GeoPolygonRenderer
                type: 'vector',
                color: '#ff0000',
            },
            customMarker: {
                // el: createEl(),
                url: testMarker,
                // keepSize: false,
                size: 100,
                // localPosition: [0, 10, 0],
                // pivot: [1, 1],
                // alwaysOnTop: false
            },
            modelCb: (obj: any) => {
                console.log('单个面创建', obj);
            },
            markerCb: (obj: any) => {
                console.log('单个marker创建', obj);
                // 添加点击事件等
            },
        });
    });
};
// 销毁地图面
const destroyGeoPolygon = () => {
    const layer = window.app.query('地图面')[0];
    if (layer) {
        layer.destroy();
    }
};
// 加载boundary
const loadBoundary = () => {
    if (lineData.length === 0) return;
    lineData.forEach((line: any) => {
        const transformData = window.TiIns.Utils.transformGeoPoints({
            coordinates: JSON.parse(line.gcj02_position),
            radius: 50,
            height: 10,
            closed: true,
        });
        // 创建bounadry
        window.mapTwinsManagerIns.createGeoBoundary({
            id: line.uuid,
            name: '围栏',
            layerName: '围栏',
            coordinates: transformData,
            userData: line,
            offsetHeight: 10,
            extrudeHeight: 200,
            renderer: {
                // 参考GeoBoundaryRenderer
                imageUrl: '/test/testImg/boundary.png',
                speed: [0, 0.1],
            },
            customMarker: {
                // el: createEle(),
                url: testMarker,
                // keepSize: false,
                size: 100,
                // localPosition: [0, 10, 0],
                // pivot: [1, 1],
                // alwaysOnTop: false
            },
            modelCb: (obj: any) => {
                console.log('围栏创建', obj);
            },
            markerCb: (obj: any) => {
                console.log('围栏marker创建', obj);
                // 添加点击事件等
            },
        });
    });
};
// 删除boundary
const deleteBoundary = () => {
    const layer = window.app.query('围栏')[0];
    if (layer) {
        layer.destroy();
    }
};
// 加载RouteLine
const loadRouteLine = () => {
    if (lineData.length === 0) return;
    lineData.forEach((line: any) => {
        // 创建bounadry
        window.mapTwinsManagerIns.createGeoRouteLine({
            id: line.uuid,
            name: 'routeLine',
            layerName: 'routeLine',
            coordinates: JSON.parse(line.gcj02_position),
            image: '/test/testImg/routeLine.png',
            scroll: true,
            arrowCap: true,
            width: 100,
            userData: line,
            offsetHeight: 100,
            customMarker: {
                // el: createEle(),
                url: testMarker,
                // keepSize: false,
                size: 100,
                // localPosition: [0, 10, 0],
                // pivot: [1, 1],
                // alwaysOnTop: false
            },
            modelCb: (obj: any) => {
                console.log('routeLine创建', obj);
            },
            markerCb: (obj: any) => {
                console.log('routeLine marker创建', obj);
                // 添加点击事件等
            },
        });
    });
};
// 删除RouteLine
const deleteRouteLine = () => {
    const layer = window.app.query('routeLine')[0];
    if (layer) {
        layer.destroy();
    }
};
// 初始化孪生体管理类
const initTwinsManager = () => {
    window.twinsManagerIns = window.TiIns.CampusTwinsManager({
        app: window.app, // HTINGJS实例
        core: window.TiIns.Core,
        inEarth: true, // 在地球上加载园区时必传
        queryParam: {
            // 查询参数-查询当前场景的所有点位
            sceneId: window.campusManagerIns.curSceneData.uuid,
        },
        initCb: () => {
            // 加载完毕回调
            console.log('加载孪生体实例初始化完毕');
        },
        singleCb: (obj: any) => {
            // 统一气泡单击回调
            console.log('统一单击回调', obj);
        },
        dbCb: (obj: any) => {
            // 统一气泡双击回调
            console.log('统一双击回调', obj);
        },
        enterCb: (obj: any) => {
            console.log('统一移入回调', obj);
        },
        leaveCb: (obj: any) => {
            console.log('统一移出回调', obj);
        },
    });
};
// 加载点位-normal(常规加载) batch(批量加载) splitNormal(常规分组加载) splitBatch(分组批量加载)-默认normal
const loadTwins = (type: string) => {
    destroyTwins();
    window.twinsManagerIns.loadCurrentLevelTwins({
        mode: type,
        // customMarker: {
        //     el: createEl(),
        //     // url: testMarker,
        //     // keepSize: false,
        //     size: 2,
        //     // localPosition: [0, 5, 0],
        //     // pivot: [1, 1],
        //     // alwaysOnTop: false,
        //     singleCb: (obj)=>{
        //         console.log('气泡单击回调',obj)
        //     },
        //     dbCb: (obj)=>{
        //         console.log('气泡双击回调',obj)
        //     },
        //     enterCb: (obj) => {
        //         console.log('气泡移入回调', obj);
        //     },
        //     leaveCb: (obj) => {
        //         console.log('气泡移出回调', obj);
        //     },
        // },
        cb: () => {
            console.log('加载完毕');
        },
    });
};
// 销毁点位
const destroyTwins = () => {
    window.twinsManagerIns.destroyCurrentLevelTwins();
};
// 自定义dom
const createEl = () => {
    const div = document.createElement('div');
    div.innerHTML = `<div class="divClass" style="width:246px;height:236px;background-color: rgba(255,255,0,0.2)";
  background-repeat:no-repeat;background-size:100% 100%; padding: 25px 37px 82px 20px; box-sizing:border-box;
  font-size: 20px;">
  <div class="name" style="font-size:24px;line-height:24px;color:#000;line-height: 38px;
  padding-left: 42px;width:100%;
  overflow: hidden; text-overflow:ellipsis; white-space: nowrap;title="自定义气泡";">自定义气泡</div>
  <div class="content" style="width:100%;height:calc(100% - 42px);font-size:30px;color:#000;padding:8px;box-sizing:border-box;overflow-y:auto;">
  测试自定义
  </div>
  </div>`;
    return div;
};
onMounted(() => {
    initScene();
});
</script>

<style lang="scss" scoped>
.scene {
    overflow: hidden;
    width: 100%;
    height: 100%;

    #div3d {
        position: absolute;
        top: 0;
        left: 0;
        width: 1920px;
        height: 1080px;
    }

    div {
        color: #ffffff;
    }

    button {
        margin-right: 5px;
    }

    .btn-wrap {
        position: absolute;
        top: 30px;
        left: 50%;
        z-index: 999;
        transform: translateX(-50%);
    }
}
</style>
